<template>
    <el-container class="applet">
        <el-main class="wrapper">
            <section class="panel cms-content">
                <div class="panel-body">
                    <div class="cms-btn-group">
                        <el-button @click="list" type="primary" icon="fa fa-refresh" size="small"> 刷新</el-button>
                        <el-button @click="create" type="primary" icon="fa fa-plus" size="small"> 新增</el-button>
                        <el-button type="danger" icon="fa fa-trash" @click="multidel()" size="small"> 删除</el-button>
                    </div>
                    <div class="cms-search-group">
                        <div class="cms-search-item">
                            <el-input  size="medium" placeholder="请输入视频名称" v-model="params.name" class="input-with-select">
                                <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                            </el-input>
                        </div>
                        <div class="cms-search-item">
                            <el-date-picker
                                    size="medium"
                                    v-model="date"
                                    align="right"
                                    type="daterange"
                                    unlink-panels
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    :picker-options="pickerOptions" @change="pickerChange">
                            </el-date-picker>
                        </div>
                        <div class="cms-search-item" style="width: 130px">
                            <el-select size="medium" v-model="params.chanel_id" placeholder="请选择频道">
                                <el-option label="频道(默认)" value=""></el-option>
                                <el-option
                                        v-for="channel in chanels"
                                        :key="channel.id"
                                        :label="channel.name"
                                        :value="channel.id">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="cms-search-item" style="width: 120px">
                            <el-select size="medium" v-model="params.sort">
                                <el-option label="排序(默认)" value=""></el-option>
                                <el-option label="浏览量" :value="1"></el-option>
                                <el-option label="分享量" :value="2"></el-option>
                            </el-select>
                        </div>
                        <div class="cms-search-item" style="width: 120px">
                            <el-select size="medium" v-model="params.option">
                                <el-option label="推荐(默认)" value=""></el-option>
                                <el-option label="否" :value="1"></el-option>
                                <el-option label="是" :value="2"></el-option>
                            </el-select>
                        </div>
                        <div class="cms-search-item" style="width: 120px">
                            <el-select size="medium" v-model="params.status">
                                <el-option label="状态(默认)" value=""></el-option>
                                <el-option label="上架" :value="1"></el-option>
                                <el-option label="下架" :value="2"></el-option>
                            </el-select>
                        </div>
                        <div class="cms-search-item" style="width: 130px" v-if="userInfo.id==1">
                            <el-select size="medium" v-model="params.admins" >
                                <el-option label="管理员(全部)" value=""></el-option>
                                <el-option v-for="(manage,index) in admins" :key="index" :label="manage"
                                           :value="index"></el-option>
                            </el-select>
                        </div>
                    </div>
                    <el-table v-loading="loading"
                              element-loading-text="努力加载中..."
                              element-loading-spinner="el-icon-loading"
                              @selection-change="handleSelectionChange"
                              ref="multipleTable"
                              :data="listData.data"
                              tooltip-effect="dark"
                              :border="true" style="width: 100%">
                        <el-table-column align="center" type="selection" width="50"></el-table-column>
                        <el-table-column align="center" prop="id" label="编号" width="80"></el-table-column>
                        <el-table-column prop="thumb" label="封面" width="120">
                            <template slot-scope="scope">
                                <el-popover placement="right" trigger="click">
                                    <img :src="scope.row.thumb"/>
                                    <el-button slot="reference"
                                               style="border: none;height: 50px;padding: 0;overflow: hidden">
                                        <div v-if="scope.row.option == 2" class="ribbon">
                                            <div class="wrap"><span class="ribbon6">荐</span></div>
                                        </div>
                                        <img title="点击查看原图" alt="点击查看原图" :src="scope.row.thumb"
                                             style="height: 50px;width: 100px"/>
                                    </el-button>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column label="标题" width="250">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.lock == 1" type="primary" size="small">正常</el-tag>
                                <el-tag v-if="scope.row.lock == 2" type="danger" size="small">锁定</el-tag>
                                {{scope.row.title}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="nickname" label="管理员" width="70"></el-table-column>
                        <el-table-column prop="chanel_id" label="频道" width="60">
                            <template slot-scope="scope">{{scope.row.chanel_id | channel(chanels) }}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="view" label="浏览量" width="80"></el-table-column>
                        <el-table-column align="center" prop="share" label="分享量" width="80"></el-table-column>
                        <el-table-column align="center" prop="pre" label="占比" width="80"></el-table-column>
                        <el-table-column align="center" prop="banner_text" label="轮播" width="60">
                            <template slot-scope="scope">
                                <span v-html="scope.row.banner_text"></span>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="status_text" label="状态" width="70">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.status == 1">上架</el-tag>
                                <el-tag v-else type="warning">下架</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="created_at" label="日期" width="140">
                            <template slot-scope="scope">{{ scope.row.created_at ? moment(scope.row.created_at).format('YYYY-MM-DD HH:mm') : ''}}</template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="edit(scope.row)" icon="fa fa-edit" plain>
                                    编辑
                                </el-button>
                                <!--<el-button @click="preview(scope.row.id)" icon="fa fa-send" type="success" size="mini"-->
                                           <!--plain> 预览-->
                                <!--</el-button>-->
                                <el-button v-if="scope.row.status == 1" @click="status(scope.row.id,2)"
                                           icon="fa fa-lock"
                                           type="warning" size="mini" plain> 下架
                                </el-button>
                                <el-button v-if="scope.row.status == 2" @click="status(scope.row.id,1)"
                                           icon="fa fa-unlock-alt" type="primary" size="mini" plain> 上架
                                </el-button>
                                <el-button icon="fa fa-trash" @click="destroy(scope.row.id)" type="danger" size="mini" plain>
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination :pageData="listData" :params="params" @list="list"/>
                </div>
            </section>
        </el-main>
        <el-dialog v-if="dialog.show"
                :title="dialog.title"
                custom-class="cms-dialog"
                :top="dialog.top"
                :visible.sync="dialog.show"
                :width="dialog.width">
            <el-form :model="form" size="medium" :status-icon="true" ref="form" label-width="80px">
                <el-form-item></el-form-item>
                <el-form-item required label="标题：" :rules="[{ required: true, message: '请填写视频标题', trigger: 'blur'}]" prop="title">
                    <el-input v-model="form.title"  placeholder="请填写视频标题"></el-input>
                </el-form-item>
                <el-form-item required label="短链接：" :rules="[{ required: true, message: '请填写视频链接', trigger: 'blur'}]" prop="link">
                    <el-input v-model="form.link" placeholder="请填写视频链接"></el-input>
                </el-form-item>
                <el-row :gutter="20">
                    <el-col :span="13"><el-form-item required :rules="[{ required: true, message: '请上传封面图', trigger: 'change'}]" label="封面图：" prop="thumb">
                        <el-upload
                                class="index-avatar-uploader"
                                :action="upload"
                                :headers="myHeaders"
                                :show-file-list="false"
                                name="image"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="form.thumb" :src="form.thumb"
                                 class="index-avatar">
                            <i v-else class="el-icon-plus index-avatar-uploader-icon"></i>
                        </el-upload>
                        <el-tag type="danger" style="margin-bottom:10px;">上传封面图片格式只能是 JPG | PNG | GIF</el-tag>
                        <el-tag type="danger" style="margin-bottom:10px;">上传封面图片大小不能超过 100KB!</el-tag>
                        <el-tag type="danger" style="margin-bottom:10px;">上传的封面图宽高必须是 360*288 px !</el-tag>
                    </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item required :rules="[{ required: true, message: '请选择视频频道', trigger: 'change'}]" label="频道："  prop="chanel_id">
                            <template>
                                <el-select v-model="form.chanel_id" placeholder="请选择视频频道">
                                    <el-option
                                            v-for="channel in chanels"
                                            :key="channel.id"
                                            :label="channel.name"
                                            :value="channel.id">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-form-item>
                        <el-form-item required label="推荐：" prop="option">
                            <el-radio-group v-model="form.option">
                                <el-radio border :label="1">不推荐</el-radio>
                                <el-radio border :label="2">推荐</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item required label="轮播：" prop="banner">
                            <el-radio-group v-model="form.banner">
                                <el-radio border :label="1">否</el-radio>
                                <el-radio border :label="2">是</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item required label="状态：" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio border :label="1">上架</el-radio>
                                <el-radio border :label="2">下架</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialog.show = false">取 消</el-button>
                <el-button type="primary" @click="update('form')">确 定</el-button>
              </span>
        </el-dialog>
    </el-container>
</template>

<script>
    import {mapGetters} from 'vuex';
    import {VideoList, VideoDestroy, VideoUpdate,VideoStatus,VideoPreview, OperateAll} from '@/utils/request';
    import Pagination from '@/components/pagination';
    export default {
        components: {Pagination},
        data() {
            return {
                userInfo:this.$storage.get('userinfo'),
                listData: [],//列表数据
                chanels: [
                    {id: 1, name: '美食'},
                    {id: 2, name: '情歌'},
                    {id: 3, name: '搞笑'},
                    {id: 4, name: '祝福'},
                    {id: 5, name: '社会'}
                ],
                params: {name: '', page: 1, chanel_id: '', sort: '',option: '',
                    status: '', admins: '', start: '', end: '', applet:"aikan"},
                dialog: {title: '', top: '5vh', show: false, width: '850px'},
                form:null,
                multipleSelection: [],
                myHeaders: {
                    'Authorization': 'Bearer ' + this.$storage.get('token'),
                    'Accept': 'application/json'
                },
                admins: [],
                //日期筛选
                pickerOptions: {
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '对比昨天',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                date:'',
            }
        },
        activated() {
            this.$store.dispatch('setAiKanActive', '/aikan/video');
            this.list();
            this.adminAll();
        },
        computed: {
            ...mapGetters(['loading', 'upload']),
        },
        methods: {
            //获取列表
            list() {
                this.$store.dispatch('setLoading', true);
                VideoList({params: this.params}).then((response) => {
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.$store.dispatch('setLoading', false);
                        this.listData = response.data;
                    }
                })
            },
            //所有角色
            adminAll() {
                OperateAll().then((res) => {
                    this.admins = res.data;
                })
            },
            //预览
            preview(id) {
                this.$confirm('确定要推送模板消息到手机查看吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    VideoPreview({id: id, applet: this.params.applet}).then((response) => {
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.$message.success(response.msg);
                        }
                    });
                }).catch(() => {});
            },
            // 上下架
            status(id, status) {
                VideoStatus({id: id, applet: this.params.applet, status: status}).then((res) => {
                    if (res.code) {
                        this.$message.error(res.msg);
                    } else {
                        this.list();
                    }
                })

            },
            //筛选
            search() {
                this.params.page = 1;
                this.list();
            },
            //创建
            create() {
                this.form = {
                    id: '',
                    title: '',
                    thumb: '',
                    link: '',
                    option: 2,
                    chanel_id: '',
                    status: 1,
                    banner: 1,
                    applet: this.params.applet
                };
                this.dialog.title = '新增视频';
                this.dialog.show = true;
            },
            //编辑
            edit(info) {
                this.form = {
                    id: info.id,
                    title: info.title,
                    thumb: info.thumb,
                    link: info.link,
                    option: info.option,
                    cate_id: info.cate_id,
                    chanel_id: info.chanel_id,
                    status: info.status,
                    banner: info.banner,
                    applet: this.params.applet
                };
                this.dialog.title = '编辑视频';
                this.dialog.show = true;
            },
            //更新
            update(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        VideoUpdate(this.form).then((response) => {
                            if (response.code==1) {
                                this.$message.error(response.msg);
                            } else {
                                this.$message({
                                    type: 'success',
                                    duration: '1000',
                                    message: response.msg,
                                    onClose: () => {
                                        this.dialog.show = false;
                                        this.list();
                                    }
                                });
                            }
                        });
                    }
                });
            },
            //删除
            destroy(id) {
                let msg;
                if (id.length) {
                    msg = '确定要删除选中的视频信息吗？';
                } else {
                    msg = '确定要删除该视频信息吗？';
                }
                this.$confirm(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    customClass: 'cms-message-box',
                    type: 'warning'
                }).then(() => {
                    VideoDestroy({id: id, applet: this.params.applet}).then((res) => {
                        if (res.code) {
                            this.$message.error(res.msg);
                        } else {
                            this.list();
                        }
                    });
                }).catch(() => {
                });
            },
            //上传封面
            handleAvatarSuccess(res, file) {
                this.form.thumb = res.data;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
                const isLt2M = file.size / 1024 < 100;
                if (!isJPG) {
                    this.$message.error('上传封面图片只能是 JPG | PNG | GIF格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传封面图片大小不能超过 100KB!');
                }
                let width = 360;
                let height = 288;
                const isSize = new Promise(function (resolve, reject) {
                    let _URL = window.URL || window.webkitURL;
                    let img = new Image();
                    img.onload = function () {
                        let valid = img.width === width && img.height === height;
                        valid ? resolve() : reject();
                    };
                    img.src = _URL.createObjectURL(file);
                }).then(() => {
                    return file;
                }, () => {
                    this.$message.error('上传的封面图宽高必须是' + width + '*' + height + ' PX !');
                    return Promise.reject();
                });
                return isJPG && isLt2M && isSize;
            },
            // 多选删除
            multidel() {
                if (this.multipleSelection.length == 0) {
                    this.$message.error('请至少选择一项你要删除的项');
                    return false;
                }
                this.destroy(this.multipleSelection);
            },
            handleSelectionChange(val) {
                let select = [];
                if (val.length > 0) {
                    val.filter((item) => {
                        if (select.indexOf(item.id) === -1) {
                            select.push(item.id)
                        }
                    });
                    this.multipleSelection = select;
                } else {
                    this.multipleSelection = [];
                }
            },
            //时间筛选
            pickerChange() {
                if (this.date) {
                    this.params.start = this.moment(this.date[0]).format('YYYY-MM-DD');
                    this.params.end = this.moment(this.date[1]).format('YYYY-MM-DD');
                } else {
                    this.params.start = '';
                    this.params.end = '';
                }
            },
        },
        filters: {
            channel: function (val, data) {
                if (!val) return '';
                let name = '';
                data.filter((item) => {
                    if (item.id === val) {
                        name = item.name;
                    }
                });
                return name;
            }
        }
    }
</script>

<style scoped>
    .index-avatar-uploader .el-upload {

        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .index-avatar-uploader-icon {
        border: 1px dashed #d9d9d9;
        font-size: 28px;
        color: #8c939d;
        width: 360px;
        height: 288px;
        line-height: 288px;
        text-align: center;
    }
</style>
